package com.atguigu.srb.oss.cotroller.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.atguigu.guigu.common.exception.BusinessException;
import com.atguigu.guigu.common.result.ResultCodeEnum;
import com.atguigu.srb.oss.config.OssProperties;
import com.atguigu.srb.oss.cotroller.service.OssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file, String module) {
        String originalFilename = file.getOriginalFilename();//获取上传的文件的名称
        String objectName = module+new DateTime().toString("/yyyy/MM/dd/")
                +System.currentTimeMillis()+"_"+ UUID.randomUUID().toString().substring(0,6)
                +originalFilename.substring(originalFilename.lastIndexOf("."));
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.ACCESSKEYID, OssProperties.ACCESSKEYSECRET);

        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            //参数1：上传的文件存入到oss的桶的名称
            //参数2：上传后的文件保存在桶内的路径+文件名称
            //参数3：上传的文件流
            ossClient.putObject(OssProperties.BUCKETNAME, objectName, inputStream);
            //拼接上传成功的图片地址
            String imgUrl = "http://"+OssProperties.BUCKETNAME+".oss-cn-shanghai.aliyuncs.com/"+objectName;
            System.out.println(imgUrl);
            return imgUrl;
        } catch (Exception oe) {
            System.out.println(oe.getMessage());
            throw new BusinessException(ResultCodeEnum.UPLOAD_ERROR,oe);
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }

        }
    }

    @Override
    public void deleteFile(String path) {
        String objectName = path.substring(path.indexOf("http://" + OssProperties.BUCKETNAME + ".oss-cn-shanghai.aliyuncs.com/")
                + ("http://" + OssProperties.BUCKETNAME + ".oss-cn-shanghai.aliyuncs.com/").length());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.ACCESSKEYID, OssProperties.ACCESSKEYSECRET);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject( OssProperties.BUCKETNAME, objectName);
        } catch (Exception ce) {
            throw new BusinessException(ResultCodeEnum.OSS_DELETE_ERROR ,ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
